// 设备端口详情
<template>
  <el-dialog
    v-el-drag-dialog="{ updataFull, updataDialogWidth }"
    :fullscreen="isfullscreen"
    :append-to-body="true"
    :title="title"
    :visible="dialogVisible"
    :width="setDialogWidth('1200px')"
    class="port-dialog"
    @close="close"
    @open="open"
  >
    <div class="flex justify-end segment-list-box port-tip bgColorStyle pt-10 pb-10 topFixed">
      <!-- <div class="port-status-list mr-10 color-select">
        {{ $t('SELECTED') }}
      </div> -->
      <div
        v-for="i in dictList['PORT_STATUS']"
        :key="i.value"
        class="port-status-list mr-10"
        :class="'color-' + i.value.toLowerCase()"
      >
        {{ i.label }}
      </div>
    </div>
    <div id="port-content" class="relative" style="min-height: 400px; overflow: auto">
      <div class="flex-column mt-20">
        <div v-for="(face, faceIndex) in faceList" :key="faceIndex" class="flex port">
          <div class="port-face pt-10 pr-10" style="width: auto; max-width: 150px">
            {{ face.partFlag }}
          </div>
          <div class="flex flex-wrap align-center flex-1 borderStyle pt-10 pb-10">
            <div
              v-for="(port, portIndex) in face.portList"
              :key="portIndex"
              class="flex align-center mt-5 segment-list-box"
            >
              <span class="port-name" :title="port.portName"> {{ port.portName }}</span>
              <div
                class="topo-port"
                :class="[
                  `color-${port.status && port.status.toLowerCase()}`,
                  { 'color-select': port.selected },
                  'port-id'
                ]"
                @click.stop="portClick(port)"
                @mouseover="mouseEnter($event, port)"
                @mouseout="mouseLeave(port)"
              />
            </div>
          </div>
        </div>
      </div>
      <el-popover
        v-model="portPop"
        class="port-tooltip"
        placement="bottom"
        :style="popPosition"
      >
        <slot name="content" class="flex-1 flex-cloumn selected-port">
          <div>
            {{ $t('SELECTED_PORT') }}：{{ hoverPortData && hoverPortData.portName }}
            {{ hoverConnPortData && '；' + hoverConnPortData.portName }}
          </div>
          <div>{{ $t('SERVICE_NAME') }}：{{ !bizData ? $t('WITHOUT') : bizData.bizName }}</div>
          <div>{{ $t('SERVICE_CODE') }}：{{ !bizData ? $t('WITHOUT') : bizData.resourceCode }}</div>
        </slot>
      </el-popover>
    </div>
    <div
      v-if="portDetailVisible"
      class="port-detail"
      :class="bizPortData.side === 'A' ? 'a-side' : ''"
    >
      <div class="flex-row-reverse flex">
        <i class="el-icon-close" @click="portDetailVisible = false" />
      </div>
      <!-- 站点 -->
      <div class="flex mt-5">
        <label>{{ $t('ZONE_SIDE_SITE', { side: bizPortData.side }) }}：</label>
        <p class="flex-1">{{ bizPortData.portData.regionName }}</p>
      </div>
      <!-- 节点 -->
      <div class="flex mt-5">
        <label>{{ $t(bizPortData.side + 'NODE') }}：</label>
        <p class="flex-1">{{ bizPortData.portData.nodeName }}</p>
      </div>
      <!-- 端口 -->
      <div class="flex mt-5">
        <label>{{ $t(bizPortData.side + '_END_NODE_PORT') }}：</label>
        <div class="flex-1">
          <p>
            {{ `${bizPortData.portData.portName}(${$t(bizPortData.portData.funcType)})` }}
          </p>
          <p v-if="bizPortData.portData2 && bizPortData.portData2.portName">
            {{ `${bizPortData.portData2.portName}(${$t(bizPortData.portData2.funcType)})` }}
          </p>
        </div>
      </div>
      <div class="flex mt-5">
        <label>{{ $t((bizPortData.side === 'A' ? 'Z' : 'A') + '_END_DEVICE') }}：</label>
        <el-button type="primary" class="mini-btn" @click="goOtherSide">{{
          $t('GO_TO_SELECT')
        }}</el-button>
      </div>
    </div>
    <span slot="footer" class="flex justify-end align-center">
      <el-button
        v-if="bizBtnShow && showSide !== 'a'"
        :disabled="bizBtnDisabled"
        type="primary"
        @click="handleDeviceAndPort('a')"
      >{{ $t('SET_A_END_PORT') }}</el-button>
      <el-button
        v-if="bizBtnShow && showSide !== 'z'"
        :disabled="bizBtnDisabled"
        type="primary"
        @click="handleDeviceAndPort('z')"
      >{{ $t('SET_Z_END_PORT') }}</el-button>
      <el-button type="primary" @click="refresh">{{ $t('REFRESH') }}</el-button>
      <el-button type="primary" @click="close">{{ $t('CLOSE') }}</el-button>
    </span>
  </el-dialog>
</template>
<script>
  import { mapGetters } from 'vuex'
  import nodeApi from '@/api/oen/NodeApi'
  import clusterApi from '@/api/afs/ClusterApi'
  import topoPositionApi from '@/api/oen/TopoPositionApi'
  import segmentChannelApi from '@/api/oen/SegmentChannelApi'
  import { getParentsById, deepClone } from '@/utils/common'

  export default {
    props: {
      dialogVisible: {
        type: Boolean,
        default: false
      },
      operateType: {
        type: String,
        default: ''
      },
      node: {
        type: Object,
        default: () => {}
      },
      formData: {
        type: Object,
        default: () => {}
      },
      // 临时用，获取设备所在机房
      station: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        faceList: [],
        regionName: '', // 设备所属区域
        linkRecommend: false,
        selectedPortData: null,
        connPortData: null,
        hoverPortData: null,
        hoverConnPortData: null,
        bizData: null,
        transPort: [],
        portPop: false,
        popPosition: {
          left: 0,
          top: 0
        },
        bizPortData: {
          side: '',
          portData: {},
          portData2: null
        },
        portDetailVisible: false,
        showSide: '',
        nodeData: {}
      }
    },
    computed: {
      ...mapGetters(['dictList', 'regionTree', 'dictMap']),
      title() {
        return `${this.dictMap['NODE_TYPE'][this.nodeData.nodeType] || ''}-${this.regionName}/${
          this.nodeData.label
        }`
      },
      bizBtnShow() {
        // console.log(this.operateType, this.nodeData)
        return (
          this.operateType === 'open' &&
          (this.nodeData.nodeCategory === 'TRANSPORT' || this.nodeData.nodeCategory === 'LIGHT_SPLIT')
        )
      },
      bizBtnDisabled() {
        return !this.selectedPortData || this.selectedPortData.status !== 'CONN'
      }
    },
    mounted() {
      this.nodeData = deepClone(this.node)
      this.getDevicePort() // 获取端口list
      this.getTransPortList()
      const regionList = (
        getParentsById(this.regionTree, this.nodeData.regionId, 'regionId') || []
      ).reverse()
      this.regionName = regionList.map(i => i.regionName).join('/')
      this.$nextTick(() => {
        document.getElementById('port-content').addEventListener('click', e => {
          this.refresh()
        })
      })
      this.open()
    },
    methods: {
      open() {
        console.log('this.formData', this.formData)
        this.showSide = ''
        const sidList = []
        this.formData.aPortData && sidList.push('a')
        this.formData.zPortData && sidList.push('z')
        if (sidList.length === 1) {
          this.showSide = sidList.join()
        }
      },
      refresh() {
        this.getDevicePort()
        this.selectedPortData = null
        this.connPortData = null
        this.hoverPortData = null
        this.hoverConnPortData = null
        this.bizData = null
        this.portPop = false
      },
      // 查询设备所有端口
      getDevicePort() {
        if (this.nodeData.nodeCategory === 'AFS' && this.nodeData.nodeType === 'CLUSTER') {
          // 集群
          clusterApi.clusterExtPort({ clusterId: this.nodeData.nodeId }).then((res = []) => {
            let portList = []
            res.devices.forEach(i => {
              const ports = i.ports.map(j => {
                const partFlag =
                  i.cabinetName +
                  '-' +
                  i.deviceName +
                  '-' +
                  j.partFlag.replace('M', 'B') +
                  this.$t('FACE')
                return {
                  ...j,
                  partFlag: partFlag
                }
              })
              portList = [...portList, ...ports]
            })
            // console.log(portList, 'portList')
            this.handlePorts(portList)
          }).catch(err => {
            console.log(err)
          })
        } else if (this.nodeData.nodeCategory === 'TRANSPORT') {
          nodeApi.transPortInfo({ nodeId: this.nodeData.nodeId }).then(res => {
            if (res) {
              const list = []
              res.forEach(i => {
                i.slotList.forEach(j => {
                  j.netPortList.forEach(z => {
                    z.portList.forEach(f => {
                      list.push({
                        ...f,
                        id: f.portId,
                        partFlag: i.shelfName + '-' + j.slotName,
                        partPortNo: z.portNo
                      })
                    })
                  })
                })
              })
              this.handlePorts(list)
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          nodeApi
            .portList({ nodeId: this.nodeData.nodeId })
            .then(res => {
              if (res && res.length) {
                this.handlePorts(res)
              }
            })
            .catch(err => {
              console.log(err)
            })
        }
      },
      handlePorts(ports) {
        // 根据设备类型不同处理端口
        this.faceList = []
        if (this.nodeData.nodeCategory === 'LIGHT_SPLIT') {
          // 光分设备

          const faceData = {
            partFlag: this.$t('NODE_LIGHT_SPLIT'),
            portList: []
          }
          ports.forEach(i => {
            const item = {
              selected: false,
              portName: this.$utils.handleServiceI18n(i.bizName),
              portId: i.portId,
              status: i.status || 'IDLE'
            }
            if (i.portName.indexOf('IN') !== -1) {
              faceData.portList.push(item)
            } else {
              // 智能开通不显示输出端口
              if (this.operateType !== 'open') {
                faceData.portList.push(item)
              }
            }
          })
          this.faceList.push(faceData)
        } else {
          // 数据组装成数结构
          const portTree = []
          ports.forEach(i => {
            const portItem = {
              ...i,
              selected: false,
              portName: this.$utils.handleServiceI18n(i.bizName),
              status: i.status || 'IDLE'
            }
            // 查询已有树结构里面是否有当前面
            const faceData = portTree.find(j => j.partFlag === i.partFlag)
            if (faceData) {
              faceData.portList.push(portItem)
            } else {
              portTree.push({
                partId: i.partId,
                partFlag: i.partFlag,
                portList: [portItem]
              })
            }
          })
          this.faceList = portTree
        }
      },
      mouseLeave() {
        this.portPop = false
        this.timer && clearTimeout(this.timer)
        if (!this.bizBtnShow && this.hoverPortData) {
          this.hoverPortData.selected = false
          this.hoverConnPortData && (this.hoverConnPortData.selected = false)
        }
        this.hoverPortData = null
        this.hoverConnPortData = null
        this.timer = null
      },
      mouseEnter(event, currentPort) {
        this.timer = setTimeout(() => {
          this.portHover(event, currentPort)
        }, 100)
      },
      // 端口点击事件
      portClick(currentPort) {
        // console.log('event', event)
        // console.log('currentPort', currentPort)
        if (!this.bizBtnShow) return
        const select = currentPort.selected
        this.selectedPortData && (this.selectedPortData.selected = false)
        this.connPortData && (this.connPortData.selected = false)
        this.selectedPortData = null
        this.connPortData = null
        if (select) return
        currentPort.selected = true
        this.selectedPortData = currentPort
        this.connPortData = this.getConnPort(currentPort)
        this.connPortData && (this.connPortData.selected = true)
      },
      portHover(event, currentPort) {
        this.portDetailVisible = false
        // console.log('event', event)
        const body = document.body
        // console.log('body', body.clientWidth)
        const left = event.pageX + 300 > body.clientWidth ? body.clientWidth - 300 : event.pageX
        this.popPosition = {
          left: left + 'px',
          top: event.pageY + 2 + 'px'
        }
        this.bizData = null
        // console.log('currentPort', currentPort)
        this.getBizInfo(currentPort)
        this.hoverPortData = currentPort
        this.portPop = true
        this.hoverConnPortData = this.getConnPort(currentPort)
        if (!this.bizBtnShow) {
          this.hoverPortData.selected = true
          this.hoverConnPortData && (this.hoverConnPortData.selected = true)
        }
      },
      getConnPort(currentPort) {
        let connData = null
        if (this.nodeData.nodeCategory === 'TRANSPORT') {
          const faceData = this.faceList.find(i => i.partFlag === currentPort.partFlag)
          console.log('portList', faceData)
          const protData = faceData.portList
            ? faceData.portList.find(
              i => i.partPortNo === currentPort.partPortNo && i.id !== currentPort.id
            )
            : null
          connData = protData
        }
        return connData
      },
      // 获取端口关联业务信息
      async getBizInfo(portData) {
        // 空闲和成端的端口不查
        if (portData.status === 'IDLE' || portData.status === 'CONN') return
        if (portData.bizData) {
          this.bizData = portData.bizData
          return
        }
        const res = await topoPositionApi.getBizByPort({
          portId: portData.portId,
          hideLoading: true
        })
        this.bizData = res || null
        portData.bizData = deepClone(res) || null
      },
      getTransPortList() {
        // 传输设备通过选择的节点获取节点下端口信息
        let nodePorts = []
        if (this.nodeData.nodeCategory === 'TRANSPORT') {
          const shelfList = this.nodeData.properties.trans.shelfList
          shelfList.forEach(i => {
            i.slotList.forEach(j => {
              j.netPortList.forEach(z => {
                if (z.isInsert) {
                  // 双芯端口添加配对端口id
                  if (z.interfaceType === 'DOUBLE') {
                    z.litPortList[0].interfaceType = z.interfaceType
                    z.litPortList[0].doublePortId = z.litPortList[1].portId
                    z.litPortList[1].doublePortId = z.litPortList[0].portId
                    z.litPortList[1].interfaceType = z.interfaceType
                  } else {
                    z.litPortList[0].interfaceType = z.interfaceType
                    z.litPortList[0].doublePortId = ''
                  }
                  nodePorts = [...nodePorts, ...z.litPortList]
                }
              })
            })
          })
        }
        this.transPort = nodePorts
      },
      close() {
        this.$emit('update:dialogVisible', false)
      },
      bizPortSet(data, side) {
        const otherSide = side === 'a' ? 'z' : 'a'
        const otherSidePort = this.formData[otherSide + 'PortData']
        if (otherSidePort) {
          if (data.portData.interfaceType !== otherSidePort.interfaceType) {
            this.$message.closeAll()
            this.$message.error(this.$t('AZ_INTERFACETYPE_CANNOT_SAME'))
            return
          }
          if (data.portData.nodeId === otherSidePort.nodeId) {
            this.$message.closeAll()
            this.$message.error(this.$t('AZ_CANNOT_SAME'))
            return
          }
          if (
            data.portData.interfaceType === 'DOUBLE' &&
            data.portData.funcType === otherSidePort.funcType
          ) {
            const portData = { ...data.portData2 }
            const portData2 = { ...data.portData }
            data.portData = portData
            data.portData2 = portData2
          }
        }
        this.formData[side + 'PortData'] = { ...data.portData }
        this.formData[side + 'PortData2'] = { ...data.portData2 }
        this.getAfsData(data.portData.portId, side)
        // console.log('this.formData', this.formData)
        if (this.formData.aPortData && this.formData.zPortData) {
          this.goOtherSide()
          return
        }
        this.bizPortData = {
          side: side.toUpperCase(),
          ...data
        }
        this.portDetailVisible = true
      },
      goOtherSide() {
        this.portDetailVisible = false
        this.$emit('close', { closeDevice: true })
      },
      // 获取选择端口连接的afs设备
      getAfsData(portId, side) {
        this.formData[side + 'AfsData'] = null
        segmentChannelApi.connNode({ portId: portId }).then(res => {
          const obj = {}
          obj[side + 'AfsData'] = res || {}
          this.formData[side + 'AfsData'] = res || {}
        }).catch(err => {
          console.log(err)
        })
      },
      handleDeviceAndPort(side) {
        // 根据用户点击的端口，用端口id去设备详情里查看这个端口是单芯还是双芯
        // 如果是单芯，就开通单芯业务
        // 如果是双芯，就开通双芯业务
        const bizPortData = {}
        const sideItem = {
          nodeType: this.nodeData.nodeType, // 端口所属设备类型
          nodeId: this.nodeData.nodeId, // 端口所属设备id
          nodeName: this.nodeData.label, // 端口所属设备名称
          regionId: this.nodeData.regionId, // 设备所属id
          regionName: this.regionName,
          portId: this.selectedPortData.portId,
          portName: this.selectedPortData.portName,
          interfaceType: 'SINGLE',
          funcType: 'SEND_RECEIVE'
        }
        if (this.nodeData.nodeCategory === 'TRANSPORT') {
          const curPortData = this.transPort.find(i => i.portId === this.selectedPortData.portId)
          bizPortData.portData = {
            ...sideItem,
            ...{
              portId: this.selectedPortData.portId,
              portName: this.selectedPortData.portName,
              interfaceType: curPortData.interfaceType,
              funcType: curPortData.funcType
            }
          }
          if (curPortData.interfaceType === 'DOUBLE') {
            // 根据端口ID找出端口对应的名字
            this.faceList.forEach((ele1, index1) => {
              ele1.portList.forEach((ele2, index2) => {
                if (ele2.portId === curPortData.doublePortId) {
                  bizPortData.portData2 = {
                    ...sideItem,
                    ...{
                      portId: curPortData.doublePortId,
                      portName: ele2.portName,
                      interfaceType: 'DOUBLE',
                      funcType: curPortData.funcType === 'SEND' ? 'RECEIVE' : 'SEND'
                    }
                  }
                }
              })
            })
            this.$message.success(this.$t('DOUBLE_CORE_PORT'))
          } else {
            bizPortData.portData2 = {}
            this.$message.success(this.$t('SINGLE_CORE_PORT'))
          }
        } else if (this.nodeData.nodeCategory === 'LIGHT_SPLIT') {
          // 光分
          // 光分只能开通单芯业务
          bizPortData.portData = sideItem
          this.$message.success(this.$t('SINGLE_CORE_PORT'))
        }
        this.bizPortSet(bizPortData, side)
      }
    }
  }
</script>
<style scoped lang="scss">
  @import '@/assets/css/mixin.module.scss';

  .port-detail {
    position: absolute;
    bottom: 60px;
    left: calc(100% - 300px);
    max-width: 300px;
    padding: 5px 10px 10px;
    @include themeify {
      background: rgba($color: themed('homeBoxBgColor'), $alpha: 0.6);
      color: themed('textColor');
      border: 1px solid themed('tableBorderColor');
    }
    &.a-side {
      left: calc(100% - 457px);
    }

    label {
      width: 95px;
    }
  }
  .port {
    &-face {
      width: 50px;
    }
    &-name {
      width: 90px;
      text-align: right;
      font-size: 12px;
      padding: 0 5px;
      // white-space: nowrap;
      white-space: pre;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    &-id {
      display: inline-block;
      width: 25px;
      height: 25px;
      border: 1px solid transparent;
      cursor: pointer;
    }
  }
  .port + .port {
    padding: 10px 0;
  }
  .port-dialog {
    overflow: hidden;
    .topFixed {
      position: sticky;
      top: -10px;
      z-index: 3000;
    }
    .port-tooltip {
      position: fixed;
      width: 300px;
      z-index: 3000;
      .el-popover {
        min-width: 200px;
      }
    }
  }
</style>
